<?php

namespace App\Kuafu\Category\Commands;

use App\Kuafu\Base\Enum\DBEnum;
use App\Kuafu\Category\Model\CategoryModel;
use App\Kuafu\Product\Model\Product;
use App\Kuafu\ProductMenu\Model\ProductMenu;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class CategoryUpgrade extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'category-upgrade';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'category模块迭代，每个菜单需要单独镜像一份category';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */
    public function handle()
    {
        // 1.所有初始分类
        $categorys = CategoryModel::query()->where('menuId', 0)->get()->toArray();

        // 2.所有菜单
        ProductMenu::query()
                   ->where('status', DBEnum::STATUS_ON)
                   ->pluck('id')
                   ->each(function ($menuId) use (
                       $categorys
                   ) {

                       foreach ($categorys as &$category) {
                           $category['menuId']    = $menuId;
                           $category['createdAt'] = $category['updatedAt'] = time();
                           unset($category['id']);
                       }

                       CategoryModel::query()->where('menuId', $menuId)->delete();
                       CategoryModel::query()->insert($categorys);
                   });

        // 3. 产品表更新categoryId
        Product::query()->where('menuId', '!=', 0)->get()->each(function($item) {

            $oriCategoryName = CategoryModel::query()->where('id',$item->categoryId)->value('name') ?? '';

            $newCategoryId = CategoryModel::query()->where('menuId', $item->menuId)->where('name', $oriCategoryName)->value('id');
            Product::query()->where('id', $item->id)->update(['categoryId' => $newCategoryId]);
        });

        Cache::flush();
    }
}
